package frontend.pages.base;

import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.util.value.ValueMap;

import frontend.core.PrometeicaWebSession;

public class LoginPage extends WebPage {

	private static final long serialVersionUID = 1L;

	public LoginPage(PageParameters parameters) {
		add(new FeedbackPanel("feedback"));
		add(new SignInForm("signInForm"));
	}

	public LoginPage() {
		this(null);
	}

	public final class SignInForm extends Form<Void> {
		private static final String USERNAME = "username";
		private static final String PASSWORD = "password";

		private final ValueMap properties = new ValueMap();

		public SignInForm(final String id) {
			super(id);

			add(new TextField<String>(USERNAME, new PropertyModel<String>(properties, USERNAME)));
			add(new PasswordTextField(PASSWORD, new PropertyModel<String>(properties, PASSWORD)));
		}

		@Override
		public final void onSubmit() {
			PrometeicaWebSession session = getMySession();

			if (session.signIn(getUsername(), getPassword())) {
				if (!continueToOriginalDestination()) {
					setResponsePage(getApplication().getHomePage());
				}
			} else {
				String errmsg = getString("loginError", null, "Invalid username and/or password");
				error(errmsg);
			}
		}

		private String getPassword() {
			return properties.getString(PASSWORD);
		}

		private String getUsername() {
			return properties.getString(USERNAME);
		}

		private PrometeicaWebSession getMySession() {
			return (PrometeicaWebSession) getSession();
		}
	}
}
